package com.cennavi.list;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.cennavi.dbs.MongoPool;
import com.cennavi.dbs.ZooKeeperConfigs;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

public class DataExportList extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4178274509719295091L;

	/**
	 * Constructor of the object.
	 */
	public DataExportList() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String ftp_ip = ZooKeeperConfigs.props.getProperty("ftp_ip_public");
		String ftp_username = ZooKeeperConfigs.props
				.getProperty("ftp_username");
		String ftp_password = ZooKeeperConfigs.props
				.getProperty("ftp_password");
		String ftp_port = ZooKeeperConfigs.props.getProperty("ftp_port");

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods",
				"POST, GET, OPTIONS, DELETE,PUT");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		try {

			String jsonStr = request.getParameter("request");

			JSONObject json = JSONObject.fromObject(jsonStr);

			String table = "data_export";

			int startPage = json.getInt("start_page");

			int pageSize = json.getInt("page_size");

			DBCollection collection = MongoPool.getDB().getCollection(table);

			BasicDBObject query = new BasicDBObject();

			// if (json.containsKey("kj_version"))
			// queryJSON.put("coord", json.getString("kj_version"));
			//
			// if (json.containsKey("time_version"))
			// queryJSON.put("version", json.getString("time_version"));

			if (json.containsKey("task_id")
					&& json.getString("task_id").length() > 0) {
				Pattern pattern = Pattern.compile(json.getString("task_id"),
						Pattern.CASE_INSENSITIVE);

				query.put("task_id", pattern);
			}

			DBCursor cursor = collection.find(query,
					(DBObject) JSON.parse("{'_id':" + 0 + "}")).sort(new BasicDBObject("task_id",-1));;

			int totalCount = (int) cursor.count();

			cursor.skip((startPage - 1) * pageSize);

			cursor.limit(pageSize);

			out.println("{\"error_code\":0,\"error_msg\":null,\"content\":{\"total_count\":"
					+ totalCount + ",\"data\":");

			out.println("[");

			boolean flag = false;

			while (cursor.hasNext()) {
				JSONObject row = JSONObject
						.fromObject(cursor.next().toString());
				if (!flag) {
					flag = true;

				} else {
					out.println(",");
				}

				if (row.getInt("status") == 1) {
					row.put("address", "  ");
				} else {

					String addStr = "{\"url\":\""
							+ ftp_ip
							+ "\",\"file_name\":\""
							+ row.getString("task_id")
							+ "\",\"user\":\""
							+ ftp_username
							+ "\",\"password\":\""
							+ ftp_password + "\",\"port\":" + ftp_port + "}";
					row.put("address", JSONObject.fromObject(addStr));
				}

				out.println(row.toString());
			}

			out.println("]");

			out.println("}");

			out.println("}");

		} catch (Exception e) {
			out.println("{\"error_code\":-1,\"error_msg\":\"" + e.getMessage()
					+ "\"}");
		} finally {
			out.flush();

			out.close();
		}

	}

	public void init() throws ServletException {
		// Put your code here
	}

}
